# -*- coding: UTF-8 -*-
# Author: Liang Bing
# E-mail: believer19940901@gmail.com
# Date Time: 2025/6/23 21:39

import json
from pathlib import Path

import click
import pandas as pd

from biobee.configs import RSCRIPT, SCRIPTS
from biobee.utils import run_or_die, open_excel


def convert_input(input_path: Path, output_path: Path):
    df: pd.DataFrame = open_excel(input_path)
    df.columns = ["X", "Y"]  # 确保一致
    df.to_csv(output_path, index=False, header=True, encoding="utf-8")
    click.echo(f"[✓] 输入文件已转换为 CSV：{output_path}")


@click.command("BasicBarplot", help="基础条形图")
def basic_barplot():
    try:
        config_path = Path("./output/result.json").absolute()
        with open(config_path, "r", encoding="utf-8") as f:
            config_dict: dict = json.load(f)

        # 准备目录
        input_dir = Path("./input").absolute()
        output_dir = Path("./output").absolute()
        log_dir = Path("./log").absolute()
        input_dir.mkdir(parents=True, exist_ok=True)
        output_dir.mkdir(parents=True, exist_ok=True)
        log_dir.mkdir(parents=True, exist_ok=True)

        # 准备路径
        input_file = input_dir / config_dict.get("inputFile", "input.xlsx")
        input_csv = output_dir / "result.csv"
        output_pdf = output_dir / "result.pdf"
        output_png = output_dir / "result.png"
        plot_sh = log_dir / "plot.sh"
        plot_log = log_dir / "plot.log"

        # 转换输入文件
        convert_input(input_file, input_csv)

        # 构建命令
        script_path = SCRIPTS / "Barplot" / "BasicBarplot" / "BasicBarplot.R"
        cmd = (
            f"#!/usr/bin/env bash\n\n"
            f"set -vex\n\n"
            f"{RSCRIPT} {script_path } "
            f"--config_json '{config_path}' "
            f"--input_csv '{input_csv}' "
            f"--output_pdf '{output_pdf}' "
            f"--output_png '{output_png}'\n\n"
            f"cd ./output \n\n"
            f"[ -f result.zip ] && rm result.zip \n\n"
            f"zip -r result.zip ./*\n\n"
        )

        # 执行
        click.echo(f"[✓] 开始执行绘图任务...")
        run_or_die(cmd=cmd, sh_file=plot_sh, log_file=plot_log)
        click.echo(f"[✓] 任务完成，结果已生成：\nPDF: {output_pdf}\nPNG: {output_png}")

    except Exception as e:
        click.echo(f"[✗] 绘图任务失败：{e}", err=True)
        raise click.Abort()
